package com.hfut.wxy.service.impl;

import com.hfut.wxy.common.parent.ParentService;
import com.hfut.wxy.entity.mysql.WxyAddress;
import com.hfut.wxy.service.IAddressService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(rollbackFor = Exception.class)
public class AddressServiceImpl extends ParentService implements IAddressService {

    @Override
    public Object getAddress(Integer userId) {
        return addressDao.findAllByUserId(userId);
    }

    @Override
    public Object addAndUpdateAddress(WxyAddress address) {
        if (address.getIsDefault()){
            WxyAddress aTrue = addressDao.findByUserIdAndIsDefaultTrue(address.getUserId());
            if (aTrue!=null) {
                aTrue.setIsDefault(false);
                addressDao.save(aTrue);
            }
        }
        return addressDao.save(address);
    }

    @Override
    public void deleteAddress(Integer id) {
         addressDao.deleteById(id);
    }

    @Override
    public Object getAllPickUpAddress() {
        return pickUpAddressDao.findAll();
    }

    @Override
    public boolean updateDefaultAddress(Integer userId, Integer addressId) {
        WxyAddress defaultAddress = addressDao.findByUserIdAndIsDefaultTrue(userId);
        defaultAddress.setIsDefault(false);
        addressDao.save(defaultAddress);
        WxyAddress byId = addressDao.getById(addressId);
        byId.setIsDefault(true);
        addressDao.save(byId);
        return false;
    }

    @Override
    public Object schools() {
        return schoolDao.findAll();
    }
}
